package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.commom.R;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.YddUserService;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/home")
public class LoginContoller {
    @Autowired
    private YddUserService yddUserService;

    /**
     * 前台登录
     * @param yddUser
     * @return
     */
    @PostMapping("/index/login")
    public R login(@RequestBody YddUser yddUser) {
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<YddUser>().eq(YddUser::getMobile, yddUser.getMobile());
        if (yddUserService.getOne(wrapper) == null) {
            return R.error("账号不存在");
        }
        String password = yddUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        wrapper.eq(YddUser::getPassword, password);
        YddUser user = yddUserService.getOne(wrapper);
        if (user == null) {
            return R.error("密码不正确");
        }
        Map map = new HashMap();
        map.put("userId",user.getId());

        String token = JwtUtils.getToken(map);
        Map tokenMap = new HashMap();
        tokenMap.put("token",token);
        return R.success("登录成功",tokenMap);
    }
}
